const path = require("path");
const { TEMP_DIR, mergeChunks, PUB_DIR } = require("../utils/uploadUtils");
const fs = require("fs-extra");
const { toTime, poolQuery } = require("../utils/utils");

/** 上传图片 接口--------------旧版---------------------*/
/** 上传图片 接口--------------旧版---------------------*/
/** 上传图片 接口--------------旧版---------------------*/
const oldUploads = (req, res) => {
  res.send({
    code: 200,
    message: "上传成功",
    data: "/uploads/" + req.file.filename, // 上传成功的服务器的地址 （上文中文件所在地址）
  });
};

/** 上传图片 接口--------------新版（分片上传）---------------------*/
/** 上传图片 接口--------------新版（分片上传）---------------------*/
/** 上传图片 接口--------------新版（分片上传）---------------------*/
const newUploads = async (req, res) => {
  let { filename, chunkname } = req.params;
  let start = Number(req.params.start);
  let chunk_dir = path.resolve(TEMP_DIR);
  let exist = await fs.pathExists(chunk_dir);
  if (!exist) {
    await fs.mkdirs(chunk_dir);
  }
  let chunkFilePath = path.resolve(chunk_dir, filename); // 分块的文件存储路径
  let ws = fs.createWriteStream(chunkFilePath, { flags: "a", start });
  req.on("end", () => {
    ws.close();
    res.json({ code: 200, message: "分片上传成功！" });
  });
  req.on("error", () => {
    ws.close();
  });
  req.on("close", () => {
    ws.close();
  });
  req.pipe(ws);
};

/** 合并 图片 */
/** 合并 图片 */
/** 合并 图片 */
const mergeImg = async (req, res) => {
  // http://47.104.71.122:8088
  let { filename, phone } = req.params;
  const sql = `INSERT INTO tyz_photo (photo,photo_name, phone, create_time, is_shoucang )
VALUES
	('http://127.0.0.1:8088/uploads/${filename}' , '${filename}',
	'${phone}','${toTime()}', '0' )`;
  await poolQuery(sql, res);
  await mergeChunks(filename);
  res.send({ code: 200, message: "上传成功" });
};

/** 查询图片上传进度  */
/** 查询图片上传进度  */
/** 查询图片上传进度  */
const verifyImg = async (req, res) => {
  let { filename } = req.params;
  let isDone = await fs.pathExists(path.resolve(PUB_DIR, filename));
  // 如果合并后的文件存在 那么说名不需要上传了
  if (isDone) {
    res.send({
      code: 200,
      message: "图片已上传!",
    });
    return;
  }
  /**
   * 上传文件的路径/文件名
   * @tempDir :server\public\uploadsHooks\d0096fc9a479f46d2e8ddb769a0484e9.png
   */
  let tempDir = path.resolve(TEMP_DIR, filename);
  let uploadList = [];
  let tempExist = await fs.pathExists(tempDir);
  // 如果存在说明之前上传过
  if (tempExist) {
    uploadList = await fs.readdir(tempDir);
    uploadList = await Promise.all(
      uploadList.map(async (filename) => {
        // 读取每一个已经上传过的分块的文件大小
        let stat = await fs.stat(path.resolve(tempDir, filename));
        return {
          filename,
          size: stat.size, // 目前上传的大小
        };
      })
    );
  }
  res.send({
    code: 200,
    message: "图片查询成功",
    needUpLoad: true,
    uploadList,
  });
};

module.exports = {
  oldUploads,
  newUploads,
  mergeImg,
  verifyImg,
};
